package com.nulldev.util.net.irc.numeric;

import com.nulldev.util.net.irc.Channel;
import com.nulldev.util.net.irc.Connection;
import com.nulldev.util.net.irc.Mode;
import com.nulldev.util.net.irc.Server;
import com.nulldev.util.net.irc.User;
import com.nulldev.util.net.irc.utils.IRCUtils;
import com.nulldev.util.threading.legacy.ThreadExecutor;

public class ChannelNickList implements Connection.NumericHandler {

	public boolean applies(Connection connection, int numeric) {
		return numeric == 353;
	}

	@Override
	public void process(Connection connection, String line, String[] parts) {
		String[] nicks = line.substring(line.lastIndexOf(':') + 1).split(" ");

		Server srv = connection.getServer();

		// parts[4] = channel name
		final Channel channel = srv.getChannel(parts[4]);
		for (String nick : nicks) {
			Mode.Type _rank = null;
			if (IRCUtils.isRank(nick.charAt(0))) {
				_rank = IRCUtils.rankFromChar(nick.charAt(0));
				nick = nick.substring(1);
			}
			final User user = srv.getUser(nick, true);
			channel.addUser(user);
			user.addChannel(channel);
			if (_rank != null) {
				final Mode.Type rank = _rank;
				ThreadExecutor.execute(new Runnable() {
					@Override
					public void run() {
						user.addChannelRank(channel, rank);
					}
				});
			}
		}
	}

}
